import {Component, OnInit} from '@angular/core';
import {FormControl, FormGroup} from "@angular/forms";
import {BarnSql} from "../entity/barn-sql";
import {BarnSqlService} from "../service/barn-sql.service";
import {NzMessageService} from "ng-zorro-antd/message";
import {BarnProduct} from "../../product/entity/barn-product";
import {ProductService} from "../../product/service/product.service";
import {Constants} from "../../../../../tools";

@Component({
  selector: 'app-my-sql',
  templateUrl: './my-sql.component.html',
  styleUrls: ['./my-sql.component.less']
})
export class MySqlComponent implements OnInit {

  validateForm = new FormGroup({
    pid: new FormControl(),
    sqlTitle: new FormControl(''),
    schemaName: new FormControl(''),
    productId: new FormControl(''),
    remark: new FormControl('')
  })

  loading = false

  sqlList: BarnSql[] = [];
  total = 1;
  current = 1;
  pageSize = 20;
  pageSizes = [this.pageSize, 50, 100]

  allProducts: BarnProduct[]


  constructor(private barnSqlService: BarnSqlService, private msg: NzMessageService, private productService: ProductService) {
  }

  ngOnInit(): void {
    this.search()
    const param = new BarnProduct();
    param.enable = Constants.Enable.YES
    this.productService.query(param).subscribe(value => {
      this.allProducts = value.data
    })
  }

  search() {
    this.loading = true
    const param = this.validateForm.getRawValue();
    this.barnSqlService.queryMySql(param, this.current, this.pageSize).subscribe(value => {
      this.sqlList = value.data
      this.current = value.current || 1
      this.total = value.count || 1
      this.loading = false
    }, () => this.loading = false)
  }

  resetForm() {
    this.validateForm.reset()
  }

  delete(pid: string) {
    this.loading = true;
    const param = new BarnSql();
    param.pid = pid;
    this.barnSqlService.deleteById(param)
      .subscribe(() => {
        this.loading = false;
        this.msg.success("删除成功")
        this.search();
      }, () => this.loading = false);
  }
}
